package com.hub.videobrowsdownload

import android.graphics.Bitmap
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.security.brows.room.BrowsWebFavoriteBean
import com.security.brows.room.BrowsWebHistoryBean

class BrowsTabWebViewModel : ViewModel() {
    var currentWebUrl = MutableLiveData("https://www.google.com")

    //        var currentWebUrl = "https://cn.pornhub.com/7035d20a-52f1-470c-b663-6a237d8f077c"
    var startWebTime = 0L
    var webTitle = MutableLiveData("")
    var webIcon:Bitmap? = null
    var webIconUrl:String? = null

    var lastWebUrl = ""

    val findVideoList = MutableLiveData<MutableList<BrowsVideoPrepare>>()
    val cacheVideoList = mutableListOf<BrowsVideoPrepare>()
    val cacheVideoUrlList = arrayListOf<String>()

    fun startNewUrl(url: String) {
        startWebTime = System.currentTimeMillis()
        Log.i("新网页开启", url)
        currentWebUrl.value = url
        clearList()
    }

    var lastVideoUrl = ""
    fun findVideoSrc(src: String) {
        if (lastVideoUrl == src) {
            return
        }
        lastVideoUrl = src
        // 先走到这里，再拆分 M3U8 和 mp4
        clearList()

        BrowsM3U8Helper.findVideoSrc(src, this)
    }

    private fun clearList() {
        try {
            if (currentWebUrl.value != lastWebUrl) {
                cancelJob()
                findVideoList.value = null
                cacheVideoUrlList.clear()
                cacheVideoList.clear()
            }
            lastWebUrl = currentWebUrl.value!!
        } catch (e: Exception) {
        }
    }

    private fun cancelJob() {
        try {
            val value = findVideoList.value
            if (!value.isNullOrEmpty()) {
                for (i in value) {
                    i.cancel()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    val refreshListHandler = android.os.Handler(Looper.getMainLooper()) {
        try {
            val toMutableList = cacheVideoList.toMutableList()
//            toMutableList.sortWith(compareBy { it.videoLength.value ?: 0L })
            findVideoList.postValue(toMutableList)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        false
    }

    fun addVideoToList(videoPrepare: BrowsVideoPrepare) {
        videoPrepare.prepare(BrowsApplication.context, webTitle.value) { type, any ->
            if (type < 0) {
                cacheVideoList.remove(videoPrepare)

                try {
                    if (any != null) {
                        if (any is List<*>) {
                            for (i in any) {
                                if (i is String) {
                                    findVideoSrc(i)
                                }
                            }
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                refreshListHandler.removeMessages(0)
                refreshListHandler.sendEmptyMessageDelayed(0, 1000)
            } else if (any is BrowsVideoPrepare) {
                cacheVideoList.add(any)
                refreshListHandler.removeMessages(0)
                refreshListHandler.sendEmptyMessageDelayed(0, 1000)
            }
        }

        refreshListHandler.removeMessages(0)
        refreshListHandler.sendEmptyMessageDelayed(0, 1000)
    }

    fun findM3U8Video(src: String) {
        if (cacheVideoUrlList.contains(src)) {
            return
        }
        cacheVideoUrlList.add(src)
        Log.i("发现测试M3U8", src)
        addVideoToList(BrowsM3U8Prepare(src, currentWebUrl.value ?: ""))
    }

    fun findMP4Video(src: String) {
        if (cacheVideoUrlList.contains(src)) {
            return
        }
        cacheVideoUrlList.add(src)
        // mp4, ogg, webm
        Log.i("发现测试MP4", src)
        addVideoToList(BrowsMP4Prepare(src, currentWebUrl.value ?: ""))
    }

    override fun onCleared() {
        cancelJob()
        super.onCleared()

    }


    fun saveHistory() {
        try {
            BrowsWebHistoryBean.save(BrowsApplication.context, startWebTime, currentWebUrl.value, webIcon, webTitle.value, webIconUrl)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    suspend fun addFavorite(): BrowsWebFavoriteBean? {
       return BrowsWebFavoriteBean.save(BrowsApplication.context, startWebTime, currentWebUrl.value, webIcon, webTitle.value, webIconUrl)
    }
}